//
//  SGHReverseList.m
//  ObjectiveCDemo20200321
//
//  Created by 远平 on 2021/11/24.
//  Copyright © 2021 远平. All rights reserved.
//

#import "SGHReverseList.h"

@implementation SGHReverseList

- (void)test {
    struct Node *list = constructList();
    printList(list);
    
    struct Node * newList = reverseList(list);
    printList(newList);
}

struct Node * reverseList(struct Node *head) {
    struct Node *p = head;
    //反转后的链表头部；
    struct Node *newH = NULL;
    //l遍历链表
    while (p != NULL) {
        //记录下一个结点
        struct Node *temp = p->next;
        p->next = newH;
        newH = p;
        p = temp;
    }
    return newH;
}

struct Node * constructList(void) {
    //头结点
    struct Node *head = NULL;
    //尾结点
    struct Node *cur = NULL;
    
    for (NSInteger i = 0; i < 10; i++) {
        
        struct Node *node = malloc(sizeof(struct Node));
        
        node->data = i;
        node->next = NULL;
        
        //头结点为空，新结点即为头结点
        if (head == NULL) {
            head = node;
        } else {
            //当前结点的next为尾结点
            cur->next = node;
        }
        
        //设置当前结点为新结点
        cur = node;
    }
    return head;
}

void printList(struct Node *head) {
    struct Node * temp = head;
    printf("list is : ");
    while (temp != NULL) {
        printf("%zd ",temp->data);
        temp = temp->next;
    }
    printf("\n");
}

@end
